import 'dart:io';

import 'package:extended_image/extended_image.dart';
import 'package:path_provider/path_provider.dart';

enum FileDir {
  compress_image(rawValue: "compress/image"),
  compress_video(rawValue: "compress/video"),
  cache_image(rawValue: "cache/image"),
  cache_video(rawValue: "cache/video"),
  download(rawValue: "yshop_download"),
  ;

  final String? rawValue;

  const FileDir({this.rawValue});
}

class FileUtils {
  static Future<String> getDir(FileDir dir) async {
    String path = "${(await getApplicationDocumentsDirectory()).path}/${dir.rawValue}/";
    if (!(await Directory(path).exists())) Directory(path).create(recursive: true);
    return path;
  }

  static Future<int> getCacheSize() async {
    String path = (await getApplicationDocumentsDirectory()).path;
    Future<int> getSize(FileDir dir) async {
      Future<int> getTotalSizeOfFilesInDir(FileSystemEntity file) async {
        if (file is File) {
          int length = await file.length();
          return int.parse(length.toString());
        } else if (file is Directory) {
          final children = file.listSync();
          int total = 0;
          for (final child in children) {
            total += await getTotalSizeOfFilesInDir(child);
          }
          return total;
        } else
          return 0;
      }

      final file = Directory("$path/${dir.rawValue}/");
      if (!(await file.exists())) return 0;
      return getTotalSizeOfFilesInDir(file);
    }

    int size = 0;
    size += await getSize(FileDir.compress_image);
    size += await getSize(FileDir.compress_video);
    size += await getSize(FileDir.cache_image);
    size += await getSize(FileDir.cache_video);
    size += await getCachedSizeBytes();
    return size;
  }

  static Future<void> clearCache() async {
    String path = (await getApplicationDocumentsDirectory()).path;
    Future<void> delete(FileDir dir) async {
      Future<void> deleteDirectory(FileSystemEntity file) async {
        if (file is Directory) {
          final children = file.listSync();
          for (final FileSystemEntity child in children) {
            await deleteDirectory(child);
            await child.delete();
          }
        }
      }

      final file = Directory("$path/${dir.rawValue}/");
      if (!(await file.exists())) return;
      await deleteDirectory(file);
    }

    await delete(FileDir.compress_image);
    await delete(FileDir.compress_video);
    await delete(FileDir.cache_image);
    await delete(FileDir.cache_video);
    await clearDiskCachedImages();
  }
}
